#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :purchase_price.py
# Time  :2025/4/8 17:19
# Email :fortunatedong@163.com
# Author:by Adonli
import json
import os
import random

import pandas as pd
import requests
from playwright.sync_api import sync_playwright

from config import ROOT_DIR,JINGDONGUSER
from utils.guotie_jd_price.jingdong_cookie import JingDongLogin



# df = pd.read_csv(jingdong_spider_purchase_sku_path)
# for i in df["商品编号"]:
#     print(i)

class GetJingDongPurchase():
    def __init__(self,username):
        self.username = username
        if self.username == "金穗隆集团":
            self.password = JINGDONGUSER[self.username]
            self.file_name = "jingdong_spider_zhuuser"
        elif self.username == "xxxxxxxxxxxxxxxx":
            self.password = JINGDONGUSER[self.username]
            self.file_name = "xxxxxxxxxxxxxxx"
        self.configs_path = os.path.join(ROOT_DIR, 'settings', 'configs.toml')
        self.jingdong_cookies_path = os.path.join(ROOT_DIR, 'utils/guotie_jd_price/auth',f'{self.file_name}_jingdong_cookies.json')
        self.stealth_min_path = os.path.join(ROOT_DIR, 'utils/guotie_jd_price/auth', 'stealth.min.js')
        self.jingdong_spider_purchase_price_path = os.path.join(ROOT_DIR, 'Datas', 'jingdong_spider_purchase_price.csv')
        self.jingdong_spider_purchase_sku_path = os.path.join(ROOT_DIR, 'Datas', 'jingdong_spider_purchase_sku.csv')
    def read_spider_jingdong_sku(self):
        df = pd.read_csv(self.jingdong_spider_purchase_sku_path, dtype=str)
        df = df[df["商品编号"].isna() == False]
        print(df)
        return df
    def read_jingdong_cookies(self):
        with open(self.jingdong_cookies_path, "r") as f:
            cookie_data = json.load(f)
            # JSESSIONID = [cookie["value"] for cookie in cookie_data if cookie["name"] == "JSESSIONID"]
            flash = [cookie["value"] for cookie in cookie_data if cookie["name"] == "flash"]
            jingdong_cookie = f"flash={random.choice(flash)};"
            return jingdong_cookie
    def sku_spider_jingdong(self,sku_code):
        count = 0
        while count < 11:
            try:
                jingdong_cookie = self.read_jingdong_cookies()
                # print(jingdong_cookie)
                header = {
                    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
                    "Cookie": f"{jingdong_cookie}",
                    "Content-type":"application/json;charset=UTF-8",

                }
                # print(header)
                params = [{
                    "bizType":"self",
                    "pageNum":1,
                    "pageSize":10,
                    "source":"2",
                    "topicCodeList":["1001"],
                    "wareIDs":[f"{sku_code}"],
                }]
                # print(params)
                response = requests.post("https://vcpps.jd.com/api/itemExtend/purchasePrice/querySkuPriceList",headers=header,json=params)
                sku_datas = response.json()['data']['data']
                # print(sku_datas)
                sku_price_data_dict = {}
                for sku_data in sku_datas:
                    if sku_data["priceTypeName"] == "基本价格":
                        wareId = sku_data["wareId"]
                        price = sku_data["price"]
                        taxFreePrice = sku_data["taxFreePrice"]
                        taxRate = sku_data["taxRate"]
                        taxPrice = sku_data["taxPrice"]
                        sku_price_data_dict = {"商品编号":wareId,"含税价":price,"不含税价":taxFreePrice,"税率":taxRate,"税额":taxPrice}
                return sku_price_data_dict
            except Exception as e:
                with sync_playwright() as pw:
                    JingDongLogin(pw, "xxxxxxxxxxxxx", "xxxxxxxxxxxxx", "guotie_jd_ziuser").save_jingdong_cookie()
                count += 1


    def skus_spider_jingdong_price(self):
        df = self.read_spider_jingdong_sku()
        sku_price_data_dicts = []
        for sku_code in df["商品编号"]:
            sku_price_data_dict = self.sku_spider_jingdong(sku_code)
            sku_price_data_dicts.append(sku_price_data_dict)
        return sku_price_data_dicts

    def save_sku_price_data_dataframe(self):
        sku_price_data_dicts = self.skus_spider_jingdong_price()
        # print(sku_price_data_dicts)
        if sku_price_data_dicts[0] != {}:
            sku_price_data_datedrame = pd.DataFrame(sku_price_data_dicts)
            print(sku_price_data_datedrame)
            sku_price_data_datedrame.to_csv(self.jingdong_spider_purchase_price_path, index=False)
            return {"code":0,"message":"成功采集"}
        else:
            sku_price_data_dicts = [{"商品编号":"","含税价":"","不含税价":"","税率":"","税额":""}]
            sku_price_data_datedrame = pd.DataFrame(sku_price_data_dicts)
            sku_price_data_datedrame.to_csv(self.jingdong_spider_purchase_price_path, index=False)
            return {"code":1,"message":"采集结果为空，检查数据源或者选择查询账号错误!"}
        # print(sku_price_data_datedrame)
# if __name__ == '__main__':
#     with sync_playwright() as pw:
#         JingDongLogin(pw, "金穗隆集团", "20250328@kinslot","jingdong_spider_zhuuser").save_jingdong_cookie()
#     GetJingDongPurchase("jd_aqrAaxqwcjCq").save_sku_price_data_dataframe()